package servlet;


import bean.GoodsBean;
import com.alibaba.fastjson.JSON;
import util.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class GoodsHuntServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int iid;
        String wname =request.getParameter("wname");
        //处理中文乱码问题
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        //获取传进来的sid和name
    try{
        iid = Integer.parseInt(request.getParameter("iid"));
        if(wname==""){
            wname="@";
        }
    }catch (Exception e){
        iid=0;
    }
        System.out.println(iid+"and"+wname);

        //获取模糊查询的数据
        String sql="SELECT * FROM inventory where iid like  ? or  wname like  ?";

        try {
            PreparedStatement ps = JdbcUtil.getConnection().prepareStatement(sql);
            ps.setInt(1,iid);
            ps.setString(2, "%"+wname+"%");
            System.out.println(ps.toString());
            ResultSet rs=ps.executeQuery();
            ArrayList<GoodsBean> arr=new ArrayList<GoodsBean>();
            while (rs.next()){
                GoodsBean gb=new GoodsBean();
                gb.setIid(rs.getInt(1));
                gb.setType(rs.getString(2));
                gb.setWid(rs.getInt(3));
                gb.setWname(rs.getString(4));
                gb.setNumber(rs.getInt(5));
                gb.setStaff(rs.getString(6));
                arr.add(gb);
            }
            String json = JSON.toJSONString(arr);
            out.print(json);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

